#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const dir = path.join(process.cwd(), 'src');
const toml = require('@iarna/toml');
let whiteList = ["r_0_1hellow_world", "script", "target"]
let arrFilter = fs.readdirSync(dir).filter(item => !item.includes('.') && !whiteList.includes(item));
let arr = arrFilter.map(item => "src/" + item)

let filePath = path.join(process.cwd(), "/Cargo.toml");


fs.access(filePath, fs.constants.F_OK, (err) => {
  // 文件不存在
  if (err) {
    let str = "[workspace] \n members = " + JSON.stringify(arr);
    fs.writeFile(filePath, str, (writeErr) => {
      if (writeErr) {
        console.error(`创建文件失败: ${writeErr.message}`);
      } else {
        console.log(`文件 ${filePath} 创建成功`);
      }
    });
    console.log(`配置文件已生成`);
  } else {
    // 文件存在，进行删除
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) {
        console.error('Error reading the file:', err);
        return;
      }
      try {
        // 解析TOML数据
        const cargoConfig = toml.parse(data);
        cargoConfig.workspace.members = arr;
        console.log(cargoConfig);
        const newData = toml.stringify(cargoConfig);
        fs.writeFile(filePath, newData, (writeErr) => {
          if (writeErr) {
            console.error('Error writing to the file:', writeErr);
          } else {
            console.log('File updated successfully.');
          }
        });
      } catch (parseErr) {
        console.error('Error parsing TOML string:', parseErr);
      }
    });
  }

})

  ;